package com.sunny.design.composite;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.List;

/**
 * @author Sunny
 * @date 2020/3/7
 */
public class Test {
    public static void main(String[] args) throws DocumentException {
        SAXReader reader = new SAXReader();
        URL url = Test.class.getResource("/composite.xml");
        Document read = reader.read(url.getFile());

        org.dom4j.Element rootElement = read.getRootElement();
        Element myRootElement = new Element(rootElement.getName(), 1);
        List<org.dom4j.Element> elements = rootElement.elements();

        add(myRootElement, 2, elements);

        myRootElement.print();
    }

    /**
     * 递归调用添加节点
     *
     * @param element 当前节点
     * @param level 层级
     * @param elements 当前节点的子节点
     */
    public static void add(Element element, int level, List<org.dom4j.Element> elements) {
        for (int i = 0; i < elements.size(); i++) {
            Element myElement = new Element(elements.get(i).getName(), level);


            List<org.dom4j.Element> childElement = elements.get(i).elements();
            if (childElement.size() > 0) {
                add(myElement, 1 + level, childElement);
            }
            element.addElement(myElement);
        }
    }
}
